<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { KeyValues } from '../../utils/types';
import { FormInstance, FormItemRule } from 'element-plus';
import { apiDict } from '../../api';
import { paramDataTypeSelect } from '../../utils/select';

const props = defineProps<{
  row?: any
}>()

const emit = defineEmits(['close', 'submitted'])

const form = ref<KeyValues>({})

const formRef = ref<FormInstance>()

const rules: { [k: string]: FormItemRule } = {
  param: { required: true, trigger: 'change', message: '请选择前段映射参数名' }
}

const close = () => emit('close')

const onOk = async () => {

  emit('submitted', { form: form.value })
}
const changeFrom = ( param )=>{
  const arr = props.row.optionValue.filter( _ => _.param === param )
  form.value = {...form.value, 
    sourceValue: arr[0].id, 
    param: arr[0].param, 
    paramType: arr[0].paramType, 
    isRequired: arr[0].isRequired,
    paramRule: arr[0].paramRule,
  }
}
const apiParamTypes = ref([])
onMounted(() => {
  if (props.row.row) {
    form.value = { ...props.row.row }
  }
  apiDict
    .getList(apiDict.DictType.PARAM_TYPE)
    .then(res => {
      apiParamTypes.value = res.rows
  })
})
</script>

<template>
  <ElDialog ref="dialogRef" title="前端映射配置">
    <ElForm ref="formRef" label-width="7em" :model="form" :rules="rules">
      <ElFormItem label="前端参数名" prop="param">
        <ElSelect v-model="form.param" @change="changeFrom">
          <ElOption v-for="(_, i) in props.row.optionValue" :key="i" :value="_.param" :label="_.param" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="前端参数类型" prop="paramType">
        <ElSelect v-model="form.paramType" disabled>
          <ElOption v-for="_ in paramDataTypeSelect.allTypes" :key="_.value" v-bind="_" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="是否必填项" prop="isRequired">
        <ElSelect v-model ="form.isRequired" disabled>
          <ElOption :value="true" label="是" />
          <ElOption :value="false" label="否" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="校验规则" prop="paramRule">
        <ElInput v-model ="form.paramRule" disabled></ElInput>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="close">取消</ElButton>
      <ElButton type="primary" @click="onOk">确定</ElButton>
    </template>
  </ElDialog>
</template>

